/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import fileio from '@ohos.fileio';
import CommonLog from './CommonLog'
import MediaUtils from './MediaUtils'


/**
 * 文件操作工具类
 */
const TAG = 'FileUtil'

export default class FileUtil {
    static isAccessPath(path): boolean{
        try {
            fileio.accessSync(path);
            return true
        } catch (err) {
            CommonLog.error(TAG, `accessSync failed,path=${path} ,error=${err}`);
            return false
        }
    }

    static isImg(name: string): boolean{
        let formats = ['.png', '.jpg', '.jpeg']
        return formats.some(format => name.includes(format))
    }

    static rmDir(path: string) {
        try {
            this.rmAllFile(path)
            fileio.rmdirSync(path)
        } catch (err) {
            CommonLog.error(TAG, `rmDir fail ,error=${err}`);
        }
    }

    static rmAllFile(path: string) {
        try {
            let dir = fileio.opendirSync(path);
            let dirent = dir.readSync()
            while (dirent) {
                CommonLog.info(TAG, `dirent name:${dirent.name}`);
                if (dirent.isDirectory()) {
                    this.rmAllFile(`${path}/${dirent.name}`)
                } else {
                    fileio.unlinkSync(`${path}/${dirent.name}`);
                }
                dirent = dir.readSync()
            }
        } catch (err) {
            CommonLog.error(TAG, `rmAllFile fail ,error=${err}`);
        }
    }

    static async getImagePath(dirPath) {
        let localImageSet = new Set()
        let imgList = [] as Array<string>
        let dir = fileio.opendirSync(dirPath);
        let dirent = dir.readSync()
        while (dirent) {
            CommonLog.info(TAG, `dirent name:${dirent.name}`);
            if (dirent.isFile() && FileUtil.isImg(dirent.name)) {
                imgList.push('file://' + dirPath + "/" + dirent.name)
                localImageSet.add(dirent.name)
            }
            dirent = dir.readSync()
        }
        CommonLog.info(TAG, `local image count ${imgList.length}`);
        try {
            // 获取媒体库图片
            let mediaFileAssets = await MediaUtils.getInstance().getMediaFileAssets()
            CommonLog.info(TAG, `mediaFileAssets image count ${mediaFileAssets.length}`);
            // 如果媒体库图片有应用目录没有的图片，那么就拷贝进去
            for (let i = 0; i < mediaFileAssets.length; i++) {
                const item = mediaFileAssets[i];
                if (!localImageSet.has(item.displayName)) {
                    CommonLog.info(TAG, `mediaFileAssets.forEach 1 ${item.displayName}`);
                    let mediaFileFd = await item.open('rw')
                    CommonLog.info(TAG, `mediaFileAssets.forEach 2 ${mediaFileFd}`);
                    fileio.copyFileSync(mediaFileFd, dirPath + '/' + item.displayName, 0)
                    CommonLog.info(TAG, `mediaFileAssets.forEach 3 `);
                    imgList.push('file://' + dirPath + '/' + item.displayName)
                    CommonLog.info(TAG, `mediaFileAssets.forEach 4 ${'file://' + dirPath + '/' + item.displayName}`);
                    await item.close(mediaFileFd)
                    CommonLog.info(TAG, `copy ${item.displayName} success`);
                } else {
                    CommonLog.info(TAG, `image has exist`);
                }
            }
            CommonLog.info(TAG, `imgList : ${JSON.stringify(imgList)}`);
        } catch (err) {
            CommonLog.error(TAG, `getMediaImage err : ${JSON.stringify(err)}`);
        } finally {
            CommonLog.info(TAG, `imgList : ${JSON.stringify(imgList)}`);
        }
        return imgList
    }
}